﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TZL.Data;

namespace TZL.Web.Controllers
{
    public class DataController : Controller
    {
        /// <summary>
        ///  Get config info
        /// </summary>
        /// <param name="configKey">Banner,VertNews,HozNews</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SelectConfig(string configKey)
        {
            try
            {
                using (var context = new PortalEntities())
                {
                    var query = (from item in context.Configs
                                 where item.ConfigKey == configKey
                                 select item).OrderByDescending(x => x.ModifyTime).ToList();

                    return Json(query);

                }
            }
            catch (Exception e)
            {
                return Json(null);
            }
        }


        #region News

        [HttpPost]
        public JsonResult SelectNews(int categoryId, int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                using (var context = new PortalEntities())
                {
                    var query = (from item in context.News
                                 where item.CategoryId == categoryId
                                 select item).OrderByDescending(x => x.PublishTime).Skip((pageIndex - 1) * pageSize).Take(pageSize);


                    return Json(query.ToList());

                }
            }
            catch (Exception e)
            {
                return Json(null);
            }
        }
        [HttpPost]
        public JsonResult SelectAllNews(int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                using (var context = new PortalEntities())
                {
                    var query = (from item in context.News
                                 select item).OrderByDescending(x => x.PublishTime).Skip((pageIndex - 1) * pageSize).Take(pageSize);


                    return Json(query.ToList());

                }
            }
            catch (Exception e)
            {
                return Json(null);
            }
        }

        [HttpPost]
        public JsonResult SelectNewsById(int newsId)
        {
            try
            {
                using (var context = new PortalEntities())
                {
                    var query = (from item in context.News
                                 where item.NewId == newsId
                                 select item).FirstOrDefault();


                    return Json(query);

                }
            }
            catch (Exception e)
            {
                return Json(null);
            }
        }

        #region 图片上传
        public ActionResult UploadImg()
        {
            var files = HttpContext.Request.Files;
            if (files.Count == 0)
            {
                var data = new { success = false, errorMessage = "没有文件" };
                return Json(data);
            }

            const string path = "/Upload/Img";

            if (!Directory.Exists(Server.MapPath(path)))
            {
                Directory.CreateDirectory(Server.MapPath(path));
            }
            var result = new List<string>();
            string absolutePath = string.Empty;
            try
            {
                for (int i = 0; i < files.Count; i++)
                {
                    var file = files[i];
                    if (file == null)
                    {
                        continue;
                    }

                    //获取文件名和文件扩展名
                    var extension = Path.GetExtension(file.FileName);

                    if (extension == null || !".jpg|.png|.jpeg|.gif".Contains(extension.ToLower()))
                    {
                        return Json(new { success = false, errorMessage = "格式错误！" });
                    }

                    string newFileName = DateTime.UtcNow.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + extension;

                    absolutePath = string.Format("{0}/{1}", path, newFileName);

                    file.SaveAs(Server.MapPath(absolutePath));

                    result.Add(absolutePath);
                }
            }
            catch (Exception e)
            {
            }

            return Json(absolutePath);
        }

        public ActionResult Upload()
        {
            var files = HttpContext.Request.Files;
            if (files.Count == 0)
            {
                var data = new { success = false, errorMessage = "没有文件" };
                return Json(data);
            }

            const string path = "/Upload";

            if (!Directory.Exists(Server.MapPath(path)))
            {
                Directory.CreateDirectory(Server.MapPath(path));
            }

            string absolutePath = string.Empty;
            try
            {
                for (int i = 0; i < files.Count; i++)
                {
                    var file = files[i];
                    if (file == null)
                    {
                        continue;
                    }

                    //获取文件名和文件扩展名
                    var extension = Path.GetExtension(file.FileName);

                    if (extension == null || !".jpg|.png|.jpeg|.gif".Contains(extension))
                    {
                        return Json(new { success = false, errorMessage = "格式错误！" });
                    }

                    string newFileName = DateTime.UtcNow.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + extension;

                    absolutePath = string.Format("{0}/{1}", path, newFileName);

                    file.SaveAs(Server.MapPath(absolutePath));
                }
            }
            catch (Exception e)
            {
            }

            var hash = new Hashtable();
            hash["error"] = 0;
            hash["url"] = absolutePath;
            return Json(hash, "text/html; charset=UTF-8");
        }
        #endregion
        #endregion


    }
}